/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package monitoring.logic;

import com.smartxls.WorkBook;
import java.util.ArrayList;
import java.util.List;
import monitoring.beans.XLS.MonitoringXLS;
import monitoring.beans.database.MonitoringDB;
import monitoring.beans.util.FileBean;
import monitoring.beans.util.ImportMessage;
import monitoring.dbpersistence.FillDependency;
import monitoring.dbpersistence.MonitoringDBPersistence;
import monitoring.dbpersistence.util.Validation;
import monitoring.mapping.XLStoDB;
import monitoring.xlspersistence.MonitoringXLSPersistence;
import org.jsoup.helper.Validate;

/**
 *
 * @author allankv
 */
public class Import {
    
    public List<ImportMessage> import_(FileBean file) throws Exception{     
        List<ImportMessage> msgs = new ArrayList<ImportMessage>();
        MonitoringXLSPersistence pXls = new MonitoringXLSPersistence();
        FillDependency d;
        List<MonitoringDB> listDB = new ArrayList<MonitoringDB>();
        
        WorkBook w = pXls.readFile("/mnt/hd/tmp/".concat(file.getFileName())); 
        String denomination = w.getText("B1");
        for (int i = 4; i < w.getLastRow() && !pXls.isEmpty(w, i); i++) {
            d = new FillDependency();  
            MonitoringXLS xls = pXls.readLine(w, i);            
            xls.setDenomination(denomination);
            for(ImportMessage msg:pXls.getMsgs())
                msgs.add(msg);
            XLStoDB m = new XLStoDB();
            MonitoringDB db = m.mapping(xls, i+1);               
            for(ImportMessage msg:m.getMsgs())
                msgs.add(msg);
            
            db = d.fillDependency(db);  
            for(ImportMessage msg:d.getMsgs())
                msgs.add(msg);
            Validation v = new Validation();
            if(v.requiredFields(db)){                
                listDB.add(db);
            }else{                
                msgs.add(v.getMsg());                
            }
        }
        
        MonitoringDBPersistence mDb = new MonitoringDBPersistence();  
        List<ImportMessage> rs = mDb.persist(listDB);
        for(ImportMessage msg:rs)
                msgs.add(msg);
        return msgs;
    }
    
}
